package net.jsoft.pms.web.mysql.goal;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import net.jsoft.platform.core.web.BaseController;
import net.jsoft.pms.entity.goal.GoalEntity;
import net.jsoft.pms.repository.goal.GoalRepository;

@Controller
@RequestMapping("/goal")
public class GoalController extends BaseController
{
    private String PREFIX = "/pms/mysql/goal/";

    @Autowired
    private GoalRepository repository;

    /**
     * 跳转到计划管理首页
     */
    @RequestMapping("/list")
    public String list()
    {
        return PREFIX + "list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject list(int pageSize, int pageNumber) throws ParseException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "percent");
        PageRequest request = new PageRequest(pageNumber - 1, pageSize, sort);
        Page<GoalEntity> list = repository.findAll(request);
        JSONObject json = new JSONObject();
        json.put("rows", list.getContent()); //这里的 rows 和total 的key 是固定的 
        json.put("total", list.getTotalElements());
        return json;
    }

    @RequestMapping("/add")
    public String add(Model model)
    {
        return PREFIX + "add";
    }

    @RequestMapping("/addSave")
    @ResponseBody
    public String addSave(GoalEntity goal) throws IOException, Exception
    {
        Date d = new Date();
        goal.setInsertDate(d);
        goal.setEditDate(d);
        repository.save(goal);
        return "ok";
    }

    @RequestMapping("/edit")
    public String edit(long id, Model model)
    {
        GoalEntity goal = repository.findOne(id);
        model.addAttribute("goal", goal);
        return PREFIX + "edit";
    }

    @RequestMapping("/editSave")
    @ResponseBody
    public String editSave(GoalEntity goal) throws ParseException
    {
        GoalEntity temp = repository.findOne(goal.getId());
        temp.setName(goal.getName());
        temp.setPercent(goal.getPercent());
        temp.setEditDate(new Date());
        repository.save(temp);
        return "ok";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(long id) throws ParseException
    {
        repository.delete(id);
        return "ok";
    }
}
